const CategoryModel = require('../model/category')

exports.add = async (req, res, next) => {
    try {
        let result = await CategoryModel.add(req.fields)
        // console.log(result);
        res.send({ status: 'success', msg: '菜品分类添加成功', data: { id: result[0].insertId } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '菜品分类添加失败' })
    }
}

exports.edit = async (req, res, next) => {
    try {
        let result = await CategoryModel.edit(req.params.id, req.fields)
        res.send({ status: 'success', msg: '菜品分类修改成功', data: { affectedRows: result[0].affectedRows } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '菜品分类修改失败' })
    }
}

exports.delete = async (req, res, next) => {
    try {
        // console.log(req.params);
        let result = await CategoryModel.delete(req.params.id)
        res.send({ status: 'success', msg: '菜品分类删除成功', data: { affectedRows: result[0].affectedRows } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '菜品分类删除失败' })
    }
}

exports.check = async (req, res, next) => {
    try {
        let result = await CategoryModel.check(req.params.category_name)
        if (result.length === 0) {
            res.send({ status: 'success', msg: '菜品分类名可用', data: result })
        } else {
            next({ status: 'fail', msg: '菜品分类名重复' })
        }
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '检查菜品分类失败' })
    }
}

exports.findById = async (req, res, next) => {
    try {
        // console.log(req.params);
        let result = await CategoryModel.findById(req.params.id)
        res.send({ status: 'success', msg: '菜品分类查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '菜品分类查找失败' })
    }
}

exports.findAll = async (req, res, next) => {
    try {
        // console.log(req.params);
        let result = await CategoryModel.findAll()
        res.send({ status: 'success', msg: '菜品分类查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '菜品分类查找失败' })
    }
}